//
//  AuditViewController.m
//  DigiOps
//
//  Created by app on 2018/7/20.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "AuditViewController.h"
#import "RTRootNavigationController.h"
#import "AuditGeneralViewController.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "AuditFinalViewController.h"
#import "XTAlertViewController.h"
#import "UserSites.h"
#import "AuditModel.h"
#import "contentListShift.h"
#import "AuditCategory.h"
#import "AuditCategoryOffline.h"
#import "AuditModel.h"
#import "PointModel.h"
#import "CustomCollectionViewCell.h"
#import "HomeViewController.h"
#import "PointValueModel.h"

@interface AuditViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,XTAlertControllerDelegate,AuditDelegate>
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)NSMutableArray *auditArray;
@property(nonatomic, strong)NSMutableArray *iconArray;

@property(nonatomic, assign)NSInteger pageSize;
@property(nonatomic, assign)NSInteger pageIndex;
@property (nonatomic,strong) UIView *headerView;
@property(nonatomic, assign)NSInteger selectIndex;
@property(nonatomic,strong)AuditModel* aModel;
@property(nonatomic,assign)int rejectCount;

@property(nonatomic, copy)NSString* pointNum;
@property(nonatomic,assign)NSString* refuseRemark;

@end
static NSString *headerViewIdentifier = @"hederview";

@implementation AuditViewController

static AuditViewController *avc = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        avc = [[self alloc] init];
    });
    return avc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _rejectCount=1;
    _selectIndex=0;
    self.submitArr=[NSMutableArray new];
    // Do any additional setup after loading the view.
//    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleBordered target:self action:@selector(clickEvent)];
//    [myButton setTintColor:[UIColor whiteColor]];
//    self.navigationItem.rightBarButtonItem = myButton;
    //提交按钮
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    
    UIButton *mainAndSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
    
    [rightButtonView addSubview:mainAndSearchBtn];
    
    [mainAndSearchBtn setImage:[UIImage imageNamed:@"overflow_icon"] forState:UIControlStateNormal];
    
    [mainAndSearchBtn addTarget:self action:@selector(clickEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    if (_model.executeState!=1)
        self.navigationItem.rightBarButtonItem = rightCunstomButtonView;
    
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"审查";
    self.navigationItem.titleView = label;
    
    self.pageSize = 20;
    self.pageIndex = 1;
    self.auditArray = [NSMutableArray array];
    self.auditArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"", nil];
//    self.auditArray=@[@"审查_通用",@"审查_标准流程",@"审查_运营及表格",@"审查_培训",@"审查_管理",@"整体审查成绩"];
    self.iconArray = [NSMutableArray array];
    self.iconArray=@[@"audit_tongyong",@"audit_liucheng",@"audit_yunying",@"audit_peixun",@"audit_guanli",@"xx"];
    [self.view addSubview:self.collectionView];
    
    /** MJRefresh的block也需要用若引用 */
    WEAKSELF
//    self.collectionView.mj_header = [XMRefreshHeader xm_headerWithRefreshingBlock:^{
//        self.pageIndex = 1;
////        [self.auditArray removeAllObjects];
//        //        [weakSelf searchAticle];
//    }];
    //默认block方法：设置上拉加载更多
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"home_message"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    
    //返回
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
    
    //签名
    if (!_model.executeState==1)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        
        [defaults    removeObjectForKey:@"audit"];
        
        [defaults   synchronize];
    }
    //调本地存储
    NSArray * array = [AuditCategory findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        [self.submitArr removeAllObjects];
        [self.submitArr addObjectsFromArray:array];
        
        //排序
//        NSArray *sortArray = [self.routeArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//
//            PointModel *pModel1 = obj1;
//            PointModel *pModel2 = obj2;
//            if (pModel1.seq > pModel2.seq) { //不使用intValue比较无效
//                return NSOrderedDescending;//降序
//            }else if (pModel1.seq < pModel2.seq){
//                return NSOrderedAscending;//升序
//            }else {
//                return NSOrderedSame;//相等
//            }
//
//        }];
//        [self.routeArray removeAllObjects];
//        self.routeArray=[NSMutableArray arrayWithArray:sortArray];
        [self.auditArray removeAllObjects];
        for (AuditCategory* ld in array) {
            [self.auditArray addObject:ld.categoryName];
        }
        [self.auditArray addObject:@"整体审查成绩"];

        //赋值sopuuid
//        for (AuditCategory* ld in array) {
//            _lineUuid=ld.lineUuid;
//            break;
//        }
        
        [self.collectionView reloadData];
        //amodel问题
        NSArray * array = [AuditModel findWhere:@[@"uuid",@"=",_model.orderTypeUuid]];
        if (array>0) {
            self.aModel=(AuditModel*)array[0];
        }
    }
    else
    {
        //离线存储
        NSArray * array1 = [AuditCategoryOffline findWhere:@[@"offlineuuid",@"=",_model.orderTypeUuid]];
        
        NSMutableArray* Temp1=[NSMutableArray new];
        for (AuditCategoryOffline* model in array1) {
            if ([model.offlineuuid isEqualToString:_model.orderTypeUuid]) {
                AuditCategory* aa=[AuditCategory new];
                aa.categoryName=model.categoryName;
                aa.categoryWeight=model.categoryWeight;
                aa.category=model.category;
                aa.score=model.score;

                aa.uuid=_model.uuid;
                aa.categoryIcon=model.categoryIcon;
                aa.categorySeq=model.categorySeq;
                [Temp1 addObject:aa];
            }
            
        }
        if (Temp1.count>0) {
            [self.submitArr removeAllObjects];
            [self.submitArr addObjectsFromArray:Temp1];
            
            //排序
                    NSArray *sortArray = [self.submitArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
                        AuditCategory *pModel1 = obj1;
                        AuditCategory *pModel2 = obj2;
                        if ([pModel1.categorySeq intValue] > [pModel2.categorySeq intValue]) { //不使用intValue比较无效
                            return NSOrderedDescending;//降序
                        }else if ([pModel1.categorySeq intValue] < [pModel2.categorySeq intValue]){
                            return NSOrderedAscending;//升序
                        }else {
                            return NSOrderedSame;//相等
                        }
            
                    }];
                    [self.submitArr removeAllObjects];
                    self.submitArr=[NSMutableArray arrayWithArray:sortArray];

            [self.auditArray removeAllObjects];
            for (AuditCategory* ld in self.submitArr) {
                [self.auditArray addObject:ld.categoryName];
            }
            [self.auditArray addObject:@"整体审查成绩"];
            
            //赋值sopuuid
            //        for (AuditCategory* ld in array) {
            //            _lineUuid=ld.lineUuid;
            //            break;
            //        }
            
            [self.collectionView reloadData];
            //amodel问题
            NSArray * array = [AuditModel findWhere:@[@"uuid",@"=",_model.orderTypeUuid]];
            if (array>0) {
                self.aModel=(AuditModel*)array[0];
            }

            return;
        }
        else{
        [self postUI];
        }
    }

}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}
-(void)goBack
{
//    if (_model.executeState==1)
//        [self searchAticle];
//    else
//    {
        NSArray * array = [AuditCategory findWhere:@[@"uuid",@"=",_model.uuid]];
        if (array.count>0) {
            //删除lineuuid的linedetail
            for (AuditCategory* pm in array) {
                [AuditCategory deleteWhere:@[@"uuid",@"=",_model.uuid]];
            }
        }
        for (AuditCategory* ld in self.submitArr) {
            [ld saveOrUpdateAsync:^(BOOL isSuccess) {
                
            }];
        }
        _model.lines=self.submitArr;

        [self.rt_navigationController popViewControllerAnimated:YES];
//    }
}

-(void)searchAticle{
    if (_model.executeState==1||_model.executeState==2) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"已提交的工单不能再次提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    for (AuditCategory* ld in self.submitArr) {
        if (ld.score==0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:[NSString stringWithFormat:@"%@打分未完成",ld.categoryName] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        else{
            if (ld.step<ld.category.count) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:[NSString stringWithFormat:@"%@打分未完成",ld.categoryName] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                return;
            }
        }
    }

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* password = [defaults objectForKey:@"audit"];
//    if (!password) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"审计人未签名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
    if (!_model.auditUser||_model.auditUser.length==0||[_model.auditUser isEqualToString:@"请填写姓名"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"审计人未签名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSArray * array = [AuditCategory findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        //删除lineuuid的linedetail
        for (AuditCategory* pm in array) {
            [AuditCategory deleteWhere:@[@"uuid",@"=",_model.uuid]];
        }
    }
    for (AuditCategory* ld in self.submitArr) {
        [ld saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    }
    _model.lines=self.submitArr;
    if (self.block) {
        self.block(_model.uuid, self.submitArr);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
}
-(void)AuditTranfer:(NSArray*) sopArr pointNum:(NSString*)pNum
{
    self.pointNum=pNum;
    NSMutableArray* auditTemp=[NSMutableArray new];
    for (AuditCategory* cat in self.submitArr) {
        if ([cat.categoryName isEqualToString:pNum]) {
            cat.category=sopArr;
        }
        [auditTemp addObject:cat];
        NSLog(@"");
    }
    [self.submitArr removeAllObjects];
    self.submitArr=auditTemp;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.selectIndex inSection:0];
    
    NSArray *indexArray=[NSArray arrayWithObject:indexPath];
    [self.collectionView reloadItemsAtIndexPaths:indexArray];
    
    NSIndexPath *indexPath5=[NSIndexPath indexPathForRow:5 inSection:0];
    
    NSArray *indexArray5=[NSArray arrayWithObject:indexPath5];
    [self.collectionView reloadItemsAtIndexPaths:indexArray5];
}
-(void)postUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];

    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectAudits"] params:nil success:^(id responseObj) {
        NSLog(@"");
        for (NSDictionary* audit in responseObj[@"content"]) {
            AuditModel* a=[AuditModel mj_objectWithKeyValues:audit];
            if ([_model.orderTypeUuid isEqualToString:a.uuid]) {
                self.aModel=a;
                //amodel取不到问题
//                [a saveOrUpdateAsync:^(BOOL isSuccess) {
//                    
//                }];
            }
            NSLog(@"");
        }
        [self.auditArray removeAllObjects];
        for (NSDictionary* template in self.aModel.category) {
            AuditCategory* cat=[AuditCategory mj_objectWithKeyValues:template];
            [self.auditArray addObject:cat.categoryName];
            //
            cat.uuid=_model.uuid;
            //提交用的数据
            [self.submitArr addObject:cat];
        }
        [self.auditArray addObject:@"整体审查成绩"];
        //
        for (NSDictionary* audit in responseObj[@"content"]) {
            AuditModel* a=[AuditModel mj_objectWithKeyValues:audit];
                //amodel取不到问题
                [a saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
            for (NSDictionary* template in a.category) {
                AuditCategoryOffline* cat=[AuditCategoryOffline mj_objectWithKeyValues:template];
                //
                cat.offlineuuid=a.uuid;
                [cat saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
            }
            NSLog(@"");
        }
        
        
        [self.collectionView reloadData];
        NSLog(@"");
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}

//gcd
-(void)gcdpost
{
    NSMutableArray* t=[NSMutableArray new];
    for (WorkOrderModel* m in self.orderCopy) {
        if (m.executeState==1&&m.workOrderType==2) {
            [t addObject:m];
        }
        if (m.executeState==2&&m.workOrderType==2) {
            [t addObject:m];
        }
    }
    [MySingleton sharedMySingleton].totalCount=[MySingleton sharedMySingleton].totalCount+t.count;
    if (t.count==0) {
        return;
    }
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    WorkOrderModel* m=(WorkOrderModel*)t[0];
    NSBlockOperation* op=[NSBlockOperation blockOperationWithBlock:^{
        [self postSubmitUI:m];
    }];
    for (int i=1; i<t.count; i++) {
        [op addExecutionBlock:^{
            [self postSubmitUI:(WorkOrderModel*)t[i]];
        }];
    }
    [op start];
}
-(void)postSubmitUI:(WorkOrderModel*)m{
    if (m.executeState==2) {
        [self postSubmitUIreject:m];
        return;
    }
    //时间问题
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    
    theDate = nowDate;
    NSString* workStart=[self eightHour:theDate];
    m.workEndDate=workStart;
    if (!m.workStartDate) {
        m.workStartDate=workStart;
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请到任务详情重新提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //            [alert show];
        //
        //        });
        //        return;
    }
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSString* password = [defaults objectForKey:@"audit"];
//    if (!password) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"审计人未签名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
    //
    NSMutableArray* content=[NSMutableArray new];

    for (AuditCategory* cat in m.lines) {
        for (PointModel* p in cat.category) {

    contentListShift* cl=[[contentListShift alloc] init];
            if (!p.auditUuid) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"分类未提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                return;
            }
    cl.templateUuid=p.auditUuid;
    cl.categoryName=cat.categoryName;
    cl.categoryWeight=cat.categoryWeight;
    cl.title=p.title;
    cl.type=p.type;
    cl.content=p.content;
    cl.remark=@"";
    cl.picture=@"";
    cl.seq=p.seq;
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    [content addObject:cl];
        }
    }
    NSArray *dictArray = [contentListShift mj_keyValuesArrayWithObjectArray:content];
    
    if (!m.workOrderRemark)
        m.workOrderRemark=@"audit";
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"score" : @20,
                             @"auditUser" : m.auditUser,
                             @"executeState" : @1,
                             @"workStartDate" : m.workStartDate,
                             @"workEndDate" : m.workEndDate,
                             @"contentList" : dictArray.mj_JSONString
                             
                             };
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];

        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)clickEvent{
    if (_model.executeState==1) {
        return;
    }
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               if (index==0) {
                                                                   [self rejectSOP];
                                                               }
                                                               else
                                                               {
                                                                   [MySingleton sharedMySingleton].reject=NO;
                                                                   [self searchAticle];
                                                               }
                                                           }];
}
- (NSArray *) titles {
    return @[@"拒绝",@"提交"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
-(void)submitSOP
{
//    [self postSubmitUI];
}
-(void)rejectSOP
{
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"拒绝工单" btnTitles:@[@"取消", @"确定"] des:@"确认拒绝工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
}
#pragma mark -
- (void)xt_alertViewControllerClickIndex:(NSInteger)buttonIndex remark:(NSString *)rem
{

    self.refuseRemark=rem;
    switch (buttonIndex) {
        case 0:
            NSLog(@"0");
            NSLog(@"Cancel");
            break;
        case 1:
            NSLog(@"1");
            NSLog(@"Determine");
            [MySingleton sharedMySingleton].reject=YES;
            [self postSubmitUIrejectEvent];
            break;
        case 2:
            NSLog(@"2");
            NSLog(@"summerxx");
            break;
        default:
            break;
    }
}
-(void)rightBarButtonItemClick
{
////    lhScanQCodeViewController * sqVC = [[lhScanQCodeViewController alloc]init];
//    //    UINavigationController * nVC = [[UINavigationController alloc]initWithRootViewController:sqVC];
//    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:sqVC];
//
//    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:nav animated:YES completion:^{
//        NSLog(@"%@");
//    }];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.auditArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CustomCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];

    cell.backgroundColor =[UIColor whiteColor];
    cell.layer.borderColor=[UIColor darkGrayColor].CGColor;
    cell.layer.borderWidth=0.3;
    
    [cell.icon setImage:[UIImage imageNamed:[self.iconArray objectAtIndex:indexPath.row]]];

    [cell.a setTitle:[self.auditArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    cell.a.tag=indexPath.row;
    [cell.a addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

    int r=indexPath.row;
    cell.index=r;
    if (indexPath.row==5) {
    
        //整体分
        double sc=0;
        for (AuditCategory* cat in self.submitArr) {
            if (cat.score) {
                sc+=cat.score;
            }
        }
        cell.score.hidden=NO;
        [cell.score setText:[NSString stringWithFormat:@"%.2f",sc]];
        cell.dangqian.hidden=YES;
        NSString* aaa=[NSString stringWithFormat:@"%.2f",sc];
        [MySingleton sharedMySingleton].finalscore=[NSString stringWithFormat:@"%.2f",sc];

    }
    else
    {
        cell.score.hidden=YES;
        cell.dangqian.hidden=NO;

    }

    //当前总得分
    double s=0.00;
    double pp=0.00;
    double high=0.00;
    if (_selectIndex==indexPath.row) {

    for (AuditCategory* cat in self.submitArr) {
        if ([cat.categoryName isEqualToString:self.pointNum]) {

        for (NSDictionary* d in cat.category) {
            PointModel* pm=[PointModel mj_objectWithKeyValues:d];
            if (pm.content&&![pm.content hasPrefix:@"["]) {

        double o=[pm.content doubleValue];
        double p=[pm.categoryWeight doubleValue];
                PointValueModel* pvm=[PointValueModel mj_objectWithKeyValues:pm.valueArr[0]];//都要mj解析什么情况
                double h=[pvm.value doubleValue];
                pp=p;
        s=s+o;
                high=high+h;

            }
        }
            NSLog(@"");
            //除以平均值
            s=s/high*pp/10.00;
            cat.score=s*10.00;
        }
    }
    }
    [cell.dangqian setTitle:[NSString stringWithFormat: @"当前得分: %@",[NSString stringWithFormat:@"%.2f",s*10.00]] forState:UIControlStateNormal];
    
    NSString* saveStep=@"";//离线修改
    if (indexPath.row<self.submitArr.count&&self.submitArr.count>0) {
        //本地存储读取
        if (self.submitArr.count>indexPath.row) {//不加会崩溃，如果中间点提交

        AuditCategory* saved=[self.submitArr objectAtIndex:indexPath.row];
        if (saved.score) {
            [cell.dangqian setTitle:[NSString stringWithFormat: @"当前得分: %@",[NSString stringWithFormat:@"%.2f",saved.score]] forState:UIControlStateNormal];
            cell.step.text=[NSString stringWithFormat:@"%d/%d",saved.step,saved.category.count];
            saveStep=[NSString stringWithFormat:@"%d/%d",saved.step,saved.category.count];
        }
        else{
            saveStep=[NSString stringWithFormat:@"%d/%d",0,saved.category.count];

        }
        }
    }
    
    NSString* b;//步数
    int st=0;
    if (_selectIndex==indexPath.row) {
        AuditCategory* cat=[self.submitArr objectAtIndex:indexPath.row];
        for (NSDictionary* pp in cat.category) {
            PointModel* p=[PointModel mj_objectWithKeyValues:pp];
            if (p.content&&![p.content hasPrefix:@"["]) {
                st++;
            }
        }
        if (cat.score>0)
            b=[NSString stringWithFormat:@"%d/%d",st,cat.category.count];
        else
            b=[NSString stringWithFormat:@"%d/%d",0,cat.category.count];
        cat.step=st;


    }
    else{
        if (indexPath.row<self.submitArr.count&&self.submitArr.count>0) {
            if (self.submitArr.count>indexPath.row) {//不加会崩溃，如果中间点提交

        AuditCategory* cat=[self.submitArr objectAtIndex:indexPath.row];
        b=[NSString stringWithFormat:@"0/%d",cat.category.count];
            cat.step=0;
            //此处加步数代码同上
            for (NSDictionary* pp in cat.category) {
                PointModel* p=[PointModel mj_objectWithKeyValues:pp];
                if (p.content&&![p.content hasPrefix:@"["]) {
                    st++;
                }
            }
            if (cat.score>0)
                b=[NSString stringWithFormat:@"%d/%d",st,cat.category.count];
            else
                b=[NSString stringWithFormat:@"%d/%d",0,cat.category.count];
            cat.step=st;
            }
        }
    }
    cell.step.text=b;
    //离线存储的
    if ([b hasPrefix:@"0"]) {
        cell.step.text=saveStep;
    }
//    [cell.scoreBar setTitle:[NSString stringWithFormat:@"%.2f",s] forState:UIControlStateNormal];

//    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
//    [cell addGestureRecognizer:tapGesture];

    return cell;
}
-(void)test:(UIButton*)sender
{
    UIButton* a=(UIButton*)sender;
    int b=a.tag;
    _selectIndex=b;
//    if (b==5) {
//        AuditFinalViewController * detailVC = [[AuditFinalViewController alloc]init];
//        detailVC.blockUser = ^(NSString *user) {
//            self.model.auditUser=user;
//        };
//        //     detailVC.model = self.aticleArray[indexPath.row];
//        [self.rt_navigationController pushViewController:detailVC animated:YES];
//    }
//    else{
        AuditGeneralViewController * detailVC = [[AuditGeneralViewController alloc]init];
        detailVC.model = self.aModel;
        detailVC.index=[self.auditArray objectAtIndex:b];
        detailVC.delegate=self;
        detailVC.ordermodel=_model;
        detailVC.block = ^(NSArray *submitArr) {
            //            self.submitArr=submitArr;
            NSLog(@"");
        };
        [self.rt_navigationController pushViewController:detailVC animated:YES];
//    }
}

-(void)tapGestureRecognizer{
    AuditGeneralViewController * detailVC = [[AuditGeneralViewController alloc]init];
         detailVC.model = self.aModel;
    detailVC.delegate=self;
    detailVC.ordermodel=_model;
    detailVC.block = ^(NSArray *submitArr) {
//        self.submitArr=submitArr;
        NSLog(@"");
    };
    [self.rt_navigationController pushViewController:detailVC animated:YES];
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    int b=indexPath.row;
    _selectIndex=b;
    if (b==5) {
        AuditFinalViewController * detailVC = [[AuditFinalViewController alloc]init];
        detailVC.model=self.model;
        detailVC.blockUser = ^(NSString *user) {
            self.model.auditUser=user;
        };
        //     detailVC.model = self.aticleArray[indexPath.row];
        [self.rt_navigationController pushViewController:detailVC animated:YES];
    }
    else{
        AuditGeneralViewController * detailVC = [[AuditGeneralViewController alloc]init];
        detailVC.model = self.aModel;
        detailVC.index=[self.auditArray objectAtIndex:indexPath.row];
        detailVC.delegate=self;
        detailVC.ordermodel=_model;
        detailVC.block = ^(NSArray *submitArr) {
//            self.submitArr=submitArr;
            NSLog(@"");
        };
        [self.rt_navigationController pushViewController:detailVC animated:YES];
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    if (indexPath.row%2==0) {
    //        return CGSizeMake(50, 50);
    //    }else{
    return CGSizeMake((self.view.bounds.size.width-90)/2, (self.view.bounds.size.width-90)/2);
    //    }
}
-(UICollectionView*)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing=20;
        layout.minimumInteritemSpacing=10;
        layout.scrollDirection=UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(90, 90);
        layout.sectionInset=UIEdgeInsetsMake(40, 30, 20, 30);
        //    MyLayout * layout = [[MyLayout alloc]init];
        //    layout.itemCount = 6;
        UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor whiteColor];
        
        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 50);
        //注册头视图
        [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];

        [collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
        collectionView.delegate=self;
        collectionView.dataSource=self;
        _collectionView=collectionView;
    }
    return _collectionView;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
        //添加头视图的内容
        [self addContent];
        //头视图添加view
        [header addSubview:self.headerView];
        return header;
    }
    //如果底部视图
    //    if([kind isEqualToString:UICollectionElementKindSectionFooter]){
    //
    //    }
    return nil;
}

/*
 *  设置头部内容
 */
-(void)addContent
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    view.backgroundColor = XMColor(241, 245, 247);
    UILabel* titleLabel = [[UILabel alloc]init];
    titleLabel.font = [UIFont xm_medium:17.0];
    titleLabel.numberOfLines = 1;
    titleLabel.textColor = [UIColor xm_jetblackColor];
    titleLabel.text=@"审查分类";
    
    [view addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).offset(18);
        make.left.equalTo(view.mas_left).offset(20);
    }];
    self.headerView=view;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)postSubmitUIrejectEvent
{
    if ([self.refuseRemark isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请填写拒绝原因" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    _model.lines=self.submitArr;
    if (self.block) {
        self.block(_model.uuid, self.submitArr);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
}


-(void)postSubmitUIreject:(WorkOrderModel*)m{
    NSMutableArray* content=[NSMutableArray new];
    
    for (AuditCategory* cat in m.lines) {
        for (NSDictionary* category in cat.category) {
            PointModel* p=[PointModel mj_objectWithKeyValues:category];

            contentListShift* cl=[[contentListShift alloc] init];
            cl.templateUuid=_model.uuid;
            cl.categoryName=cat.categoryName;
            cl.categoryWeight=cat.categoryWeight;
            cl.title=p.title;
            cl.type=p.type;
            cl.content=p.content;
            cl.remark=@"";
            cl.picture=@"";
            cl.seq=p.seq;
            //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
            [content addObject:cl];
        }
    }
    NSArray *dictArray = [contentListShift mj_keyValuesArrayWithObjectArray:content];
    
    if (!m.workOrderRemark)
        m.workOrderRemark=@"audit";
    if (!self.refuseRemark) {
        self.refuseRemark=@"拒绝";
    }
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @2,
                             @"count" : @(_rejectCount),
                             @"refuseRemark" : self.refuseRemark
                             
                             };

    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        _rejectCount++;
        _model.executeState=[@"2" integerValue];
//        HomeViewController * homeVC = [[HomeViewController alloc]init];
//        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
//        // 添加为子控制器
//        nav.title = @"任务箱";
//        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
//
//        if (self.blockReject) {
//            self.blockReject();
//        }
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rt_navigationController popViewControllerAnimated:YES];
        });
    }];
}
@end
